document.write("<script language=javascript src='/js/JsBarcode.all.min.js'></script>");
(function ($) {
    var opt = {
        canvas_weight: 300,
        canvas_height: 350,
        canvas_background_color: '#ffffff',

        qr_weight: 200,
        qr_height: 200,
        qr_typeNumber: 4,
        qr_colorDark: "#279A78",
        qr_colorLight: "#ffffff",

        lsLogo: "../lsyl.png",
        lsLogo2: "../../lsyl.png",

        dp_weight: 300,
        // correctLevel: QRCode.CorrectLevel.H,
        dp_height: 350,

        logo_weight: 35,
        logo_height: 35,
        logo_imgPath: '../lsyl.png'
    };

    $.extend({
        //获取当前机构所选 id
        getHospitalId: function () {
            console.log($("#hospital_id").val())
        },
        department: {
            init: function (options) {
                opt = $.extend(opt, options);
            },
            //预览
            preQRcode: function (name, pid) {
                generate_qrcode(pid);
                qrcode(name, 'pre', pid)
            },
            //下载
            downQRcode: function (name, pid) {
                generate_qrcode(pid);
                qrcode(name, 'download', pid)
            }
        },
        tableTemplate: {
            //添加 复杂表头模板
            header: function () {
                return {
                    title: "打印报表标题",
                    toolbar: '#toolbarDate',
                    totalRow: true,
                    defaultToolbar: [
                        {
                            title: '提示' //标题
                            , layEvent: 'PROMPT' //事件名，用于 toolbar 事件中使用
                            , icon: 'layui-icon-tips' //图标类名
                        },
                        'filter', 'exports_custom', 'print'
                    ],
                    PrExData: {
                        PrTitle: "医院产量统计报表",
                        ExTitle: "医院产量统计报表 ${date}",
                        header: [
                            {
                                type: "date",
                                float: "left",
                                size: 10,
                                index: 3,
                                dateFormat: "yyyy/MM/dd",
                                show: true,
                                text: "制表日期 ${start} 到 ${end}"
                            },
                            {
                                type: "customize",
                                float: "left",
                                size: 10,
                                index: 2,
                                show: true,
                                text: "审核人：${user}"
                            },
                            {
                                type: "customize",
                                float: "left",
                                size: 10,
                                index: 1,
                                show: true,
                                text: "医疗废物产生单位：${organization}"
                            }
                        ]
                    },
                    cols: [
                        [{
                            title: '标题',
                            field: 'bag',
                            align: 'center',
                            totalRowText: '合计',
                            totalRowType: 'int'
                        }, {
                            title: '列',
                            field: 'weight',
                            align: 'center',
                            totalRow: true,
                            totalRowType: 'int'
                        }]
                    ]
                }
            },
            //添加 普通表头模板
            complexHeader: function () {
                return {
                    title: "报表打印标题、导出文件名",
                    toolbar: '#toolbarDate',
                    totalRow: true,
                    defaultToolbar: [
                        {
                            title: '提示' //标题
                            , layEvent: 'PROMPT' //事件名，用于 toolbar 事件中使用
                            , icon: 'layui-icon-tips' //图标类名
                        },
                        'filter', 'exports_custom', 'print'
                    ],
                    cols: [
                        [{
                            title: '名称',
                            align: 'center',
                            rowspan: 2,
                            totalRowText: '合计',
                        }, {
                            title: '省份',
                            align: 'center',
                            colspan: 3
                        }, {
                            title: '统计',
                            align: 'center',
                            colspan: 3
                        }],
                        [{
                            title: '省',
                            field: 'bag',
                            align: 'center',
                            totalRow: true,
                            totalRowType: 'int'
                        }, {
                            title: '市',
                            field: 'weight',
                            align: 'center',
                            totalRow: true,
                        }, {
                            title: '县',
                            field: '',
                            align: 'center',
                        }, {
                            title: '列',
                            field: '',
                            align: 'center',
                            totalRow: true,
                            totalRowType: 'int'
                        }]
                    ]
                }
            },
            //获取日期
            dateValue: function (type) {
                var now = new Date();
                var year = now.getFullYear(); //得到年份
                var month = now.getMonth() + 1;//得到月份
                var date = now.getDate();//得到日期
                if (date < 10)
                    date = '0' + date
                if (month < 10)
                    month = '0' + month
                switch (type) {
                    case  'range':
                        return year + '-' + month + '-01 - ' + year + '-' + month + '-' + date;
                        break;
                    case 'start':
                        return year + '-' + month + '-01'
                        break;
                    case 'end':
                        return year + '-' + month + '-' + date;
                        break;
                    case 'month' :
                        return year + '-' + month
                        break;
                }
                return year + '-' + month + '-' + date;
            },
            //返回数据处理
            parseData: function () { //res 即为原始返回的数据
                return function (res) {
                    return {
                        "code": res.code, //解析接口状态
                        "msg": res.msg, //解析提示文本
                        "count": res.total, //解析数据长度
                        "data": res.rows
                    };
                }
            },
            /**
             * 数据渲染完的回调
             */
            done: function (res, curr, count, config) {
                // dones 回显后执行
                for (var key in config.dones) {
                    switch (key) {
                        //添加条形码图片
                        case '@codeIdImg' :
                            let k = config.dones[key]
                            for (let i = 0; i < res.data.length; i++) {
                                let codeid = res.data[i][k];
                                JsBarcode("img[data-id='" + codeid + "']", codeid, {
                                    format: "CODE128",
                                    height: 120,
                                    width: 10,
                                    displayValue: true,
                                    fontSize: 80
                                });
                            }
                            break;
                    }
                }
                // toolbar 控件
                switch (config.toolbar) {
                    case '#toolbarDate':  //日期监听
                        //日期控件
                        layui.laydate.render({
                            elem: "#toolbarDate_layui",
                            format: "yyyy-MM-dd",
                            max: $.tableTemplate.dateValue(),
                            value: range,
                            range: true,
                            //监听事件跨度
                            // change: function (value, date, endDates) {
                            //     console.log(value); //得到日期生成的值，如：2017-08-18
                            //     var dates = value.split(' - ');
                            //     var start = new Date(dates[0]), end = new Date(dates[1]);
                            //
                            //     var days = (end - start) / (1000 * 60 * 60 * 24);
                            //     if (days > 31) {
                            //         layer.msg('时间跨度只能选择31天', {time: 3000});
                            //         $(".laydate-btns-clear").click();
                            //     }
                            // },
                            //确定
                            done: function (value) {
                                var dates = value.split(' - ');
                                startDate = dates[0]
                                endDate = dates[1]
                                range = value
                            }
                        });
                        break;
                    case "#toolbarDate2":
                        //同时绑定多个
                        var startTime = layui.laydate.render({
                            elem: "#toolbarDate_layui_2_start",
                            format: "yyyy-MM-dd",
                            value: startDate,
                            btns: ['clear', 'now', 'confirm'],
                            showBottom: false,
                            max: endDate,
                            done: function (value, date) {
                                if (value !== "") {
                                    endTime.config.min = {
                                        year: date.year,
                                        month: date.month - 1,//关键
                                        date: date.date
                                    }
                                    startDate = value;
                                } else {
                                    endTime.config.min = {
                                        year: "1098",
                                        month: "1",
                                        date: "1"
                                    }
                                }
                            }
                        });
                        var endTime = layui.laydate.render({
                            elem: "#toolbarDate_layui_2_end",
                            format: "yyyy-MM-dd",
                            value: endDate,
                            min: startDate,
                            btns: ['clear', 'now', 'confirm'],
                            showBottom: false,
                            trigger: 'click',
                            done: function (value, date) {
                                if (value !== "") {
                                    startTime.config.max = {
                                        year: date.year,
                                        month: date.month - 1, //关键
                                        date: date.date
                                    };
                                    endDate = value;
                                } else {
                                    startTime.config.max = {
                                        year: "3019",
                                        month: "1",
                                        date: "1"
                                    };
                                }
                            },
                        });
                        break;
                    case '#toolbarMonth' :
                        layui.laydate.render({
                            elem: "#toolbarMonth_layui",
                            format: "yyyy-MM",
                            type: 'month',
                            value: month,
                            trigger: 'click',
                            //监听点击月份
                            change: function (value) {
                            },
                            //确定
                            done: function (value) {
                                month = value
                                console.log(value)
                            }
                        });
                        break
                }

                //自定义配置 XiaoYi...
                if (config.PrExData && config.PrExData != undefined) {

                    //获取科室楼号数据，并渲染
                    if (config.PrExData.buildingNoBoo && config.PrExData.buildingNoBoo != undefined) {
                        layui.form.on('select(select_buildingNo)', function (data) {
                            buildingNo = data.value
                        });
                        $("#buildingNoList").find("option[value='" + buildingNo + "']").attr("selected", true);
                        layui.form.render('select');
                    }
                    //获取采集员数据，并渲染
                    if (config.PrExData.collUserBoo && config.PrExData.collUserBoo != undefined) {
                        layui.form.on('select(select_collUser)', function (data) {
                            collUser = data.value
                        });
                        $("#collUserList").find("option[value='" + collUser + "']").attr("selected", true);
                        layui.form.render('select');
                    }
                    //获取科室数据，并渲染
                    if (config.PrExData.departmentBoo && config.PrExData.departmentBoo != undefined) {
                        layui.form.on('select(select_department)', function (data) {
                            department = data.value
                        });
                        $("#departmentList").find("option[value='" + department + "']").attr("selected", true);
                        layui.form.render('select');
                    }
                    //获取医废类型数据，并渲染
                    if (config.PrExData.yfTypeBoo && config.PrExData.yfTypeBoo != undefined) {
                        layui.form.on('select(select_yfType)', function (data) {
                            yfType = data.value
                        });
                        $("#yfTypeList").find("option[value='" + yfType + "']").attr("selected", true);
                        layui.form.render('select');
                    }
                }
            }
        },
        fullScreen: {
            //全屏
            full: function () {
                var element = document.documentElement;
                if (element.requestFullscreen) {
                    element.requestFullscreen();
                } else if (element.msRequestFullscreen) {
                    element.msRequestFullscreen();
                } else if (element.mozRequestFullScreen) {
                    element.mozRequestFullScreen();
                } else if (element.webkitRequestFullscreen) {
                    element.webkitRequestFullscreen();
                }

                //监听window是否全屏，并进行相应的操作,支持esc键退出
                var isFull = !!(document.webkitIsFullScreen || document.mozFullScreen ||
                    document.msFullscreenElement || document.fullscreenElement
                );//!document.webkitIsFullScreen都为true。因此用!!
                if (isFull == false) {
                    $(this).css("display", "none");
                }
            },
            toggleFull: function () {
                if (document.exitFullscreen) {
                    document.exitFullscreen();
                } else if (document.msExitFullscreen) {
                    document.msExitFullscreen();
                } else if (document.mozCancelFullScreen) {
                    document.mozCancelFullScreen();
                } else if (document.webkitExitFullscreen) {
                    document.webkitExitFullscreen();
                }
            }
        },
        /**
         * 获取机构等级类型
         * @param pid 机构类型
         */
        selectDeptType: function (pid) {
            //添加 页面 ==== 判断如果是医院 类型 只显示暂存点
            if (pid >= 220 && pid <= 321) {
                //只显示暂存点
                // console.log("应只选择暂存点");
                $(".deptType").show();
                $("#deptType").val('');
                $(".deptType").not(".deptType[value='400']").hide()
                $(".prompt-contract").show();
                console.log("0.0.0.0.0.")
            } else
                //判断 省卫健委
            if (pid == 110) {
                $(".deptType").show();
                $("#deptType").val('');
                $(".deptType").not(".deptType[value='120']").hide()
                // console.log("只显示市卫健委");
            } else
                //判断 市卫健委 只能创建 县卫健委
            if (pid == 120) {
                $(".deptType").show();
                $("#deptType").val('');
                $(".deptType").not(".deptType[value='130']").hide()
                // console.log("只显示县卫健委");
            } else
                //判断 区县卫健委 医院
            if (pid == 130) {
                $(".deptType").show();
                $("#deptType").val('');
                //    显示 省、市、县 医院、社区服务中心、乡镇卫生院、诊所
                $(".deptType").not(".deptType[value='220'],.deptType[value='270'],.deptType[value='290'],.deptType[value='310'],.deptType[value='320'] ").hide()
                // console.log("只显示医院");
                //判断暂存点 不能往下创建
            } else if (pid == 400) {
                //    只显示医院
                $("#deptType").val('');
                $(".deptType").hide();
                // console.log("只显示医院");
            } else {
                //否则只是省卫建委
                $(".deptType").show();
                $("#deptType").val('');
                $(".deptType").not(".deptType[value='110']").hide()
                //    其他只显示卫健委
                // console.log("只显示省卫健委");
            }
        }
    });
//todo 第一次无法打开照片 无法下载
    //创建隐藏二维码
    function generate_qrcode(qid) {
        //创建一个隐藏的div
        $('body').append('<div  class="hidden" id="qrcode_xp"></div> <canvas id="myCanvas" class="hidden"></canvas>');
        //绑定上面的div生成一个二维码
        var qrcode = new QRCode('qrcode_xp', {
            text: qid,
            width: opt.qr_weight,
            height: opt.qr_height,
            typeNumber: 4,
            colorDark: opt.qr_colorDark,
            colorLight: opt.qr_colorLight,
            correctLevel: QRCode.CorrectLevel.H
        });  // 设置要生成二维码
    }

    //验证图片是否存在
    function validateImage(url) {
        var xmlHttp;
        if (window.ActiveXObject) {
            xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
        } else if (window.XMLHttpRequest) {
            xmlHttp = new XMLHttpRequest();
        }
        xmlHttp.open("Get", url, false);
        xmlHttp.send();
        if (xmlHttp.status == 404)
            return false;
        else
            return true;
    }

    //生成科室二维码
    function qrcode(name, event, pid) {

        var logo_imgPath = '/profile/medical_waste_logo/' + pid + '.jpg'

        var qrcodeImg = document.getElementById("qrcode_xp").lastChild;
        var logo = new Image();
        logo.src = opt.logo_imgPath;
        logo.width = opt.logo_weight
        logo.height = opt.logo_height
        //判断照片是否存在
        if (!validateImage(opt.logo_imgPath)) {
            if (validateImage(opt.lsLogo)) {
                logo.src = opt.lsLogo;
            } else {
                logo.src = opt.lsLogo2;
            }
        }


        var canvas = document.getElementById("myCanvas");
        canvas.width = opt.canvas_weight;
        canvas.height = opt.canvas_height;
        var ctx = canvas.getContext("2d");
        ctx.fillStyle = opt.canvas_background_color;//设置白色 背景颜色
        ctx.fillRect(0, 0, canvas.width, canvas.height);//设置背景色范围
        logo.crossOrigin = "*";
        logo.onload = function () {
            ctx.drawImage(logo, 20, 10, logo.width, logo.height);//绘制logo
            ctx.drawImage(qrcodeImg, 50, 70, qrcodeImg.width, qrcodeImg.height);//绘制二维码
            ctx.fillStyle = '#111';//文本颜色
            ctx.font = "30px 微软雅黑";//文本字体
            var conter = (canvas.width - ctx.measureText(name).width) / 2;//文本居中位置获取
            ctx.fillText(name, conter, canvas.height - 30);//设置文本
            var base64 = canvas.toDataURL('image/jpeg')
            switch (event) {
                case 'pre':
                    showQrCode(name, base64);
                    reomeImg()
                    break;
                case 'download':
                    downLoad(name, base64);
                    reomeImg()
                    break;
                case 'base64':
                    return base64;
                    break;
            }

        }
    }

    //下载二维码
    function downLoad(name, url) {
        // console.log("downLoad:",url)
        var oA = document.createElement("a");
        oA.download = name + ".jpg";// 设置下载的文件名，默认是'下载'
        oA.href = url;
        document.body.appendChild(oA);
        oA.click();
        oA.remove(); // 下载之后把创建的元素删除
    }

    //弹出 生成二维码
    function showQrCode(name, base64) {
        // console.log("downLoad:",base64)
        layer.photos({
            skin: 'layer-photos-img',
            shade: [0.8, '#393D49'],
            area: ['auto', 'auto'],
            photos: {
                "start": 0, //初始显示的图片序号，默认0
                "data": [   //相册包含的图片，数组格式
                    {
                        "alt": name,
//                        "src": qrcode_path(qid), //原图地址
                        src: base64
                    }
                ]
            }
            , anim: 5 //0-6的选择，指定弹出图片动画类型，默认随机（请注意，3.0之前的版本用shift参数）
        });
    }

    //移除标签
    function reomeImg() {
        $('#qrcode_xp').remove();
        $('#myCanvas').remove();
    }


})(jQuery);


